<!-- 生产管理->生产订单 -->
<template>
    <div class="content-wrapper a-base-container">
        <div class="requisition-set-wrapper" style="display:block">
            <!-- 按钮 -->
            <div class="btn-wrapper clearfix">
                <btns-wrapper @searchClick="searchClick" :showModel="showModel" :orderId="orderId" :voucherState="voucherState" :editMask="editMask" @printOrder="printOrder" @switchList="switchList" @submitServer="submitServer" @clickEdit="clickEdit" @deleteOrder="deleteOrder" @getIdByData="getIdByData" @auditClick="auditClick" @turnThePage="turnThePage" @syncOrder="syncOrder" @submitOrder="submitOrder" @exportDetail="exportDetail" :sourceCode="sourceCode">
                    <template slot="neworder">
                        <a-dropdown class="btns" key="new" style="display:block">
                            <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                                <a-icon class="btns-icon" type="file-add" />
                                <div class="btns-text">新增
                                    <a-icon type="down" style="color:rgb(24,144,255);vertical-align:middle;" />
                                </div>
                            </a>
                            <a-menu slot="overlay">
                                <a-menu-item key="0">
                                    <a href="javascript:void(0)" @click="newForecast">新增</a>
                                </a-menu-item>
                            </a-menu>
                        </a-dropdown>
                    </template>
                    <!-- <template slot="guanbi">
                        <a-dropdown class="btns" key="sheng" style="display:block">
                            <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                                <a-icon class="btns-icon" type="snippets" />
                                <div class="btns-text">关闭
                                    <a-icon type="down" />
                                </div>
                            </a>
                            <a-menu slot="overlay">
                                <a-menu-item key="0">
                                    <a href="javascript:void(0)" @click="generateBills1('MasterProductionSchedule')">打开</a>
                                </a-menu-item>
                                <a-menu-item key="1">
                                    <a href="javascript:void(0)" @click="generateBills1('MasterProductionSchedule')">关闭</a>
                                </a-menu-item>
                            </a-menu>
                        </a-dropdown>
                    </template> -->

                    <template slot="shengdan">
                        <a-dropdown class="btns" key="sheng" style="display:block">
                            <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                                <a-icon class="btns-icon" type="snippets" />
                                <div class="btns-text">下达
                                    <a-icon type="down" />
                                </div>
                            </a>
                            <!-- <a-menu v-if="voucherState==1" slot="overlay"> -->
                            <a-menu slot="overlay">
                                <template v-if="[-1,0].includes(voucherState)">
                                     <a-menu-item key="0">
                                        <a href="javascript:void(0)">
                                             <span :class="'color-gray'">下达生产</span>
                                        </a>
                                    </a-menu-item>
                                    <a-menu-item key="1">
                                        <a href="javascript:void(0)">
                                            <span :class="'color-gray'">下达委外</span>
                                        </a>
                                    </a-menu-item>
                                    <a-menu-item key="2">
                                        <a href="javascript:void(0)" >
                                             <span :class="'color-gray'">下达采购</span>
                                        </a>
                                    </a-menu-item>
                                </template>
                                <template v-else>
                                    <a-menu-item key="0" v-show ='num==2?true:false'>
                                        <a href="javascript:void(0)"  @click="generateBills('ReleaseProduction',0,listArr)">下达生产</a>
                                    </a-menu-item>
                                    <a-menu-item key="1" v-show ='num==3?true:false'>
                                        <a href="javascript:void(0)"  @click="generateBills('AssignOutsourcing',1,listArr)">下达委外</a>
                                    </a-menu-item>
                                    <a-menu-item key="2" v-show ='num==1?true:false'>
                                        <a href="javascript:void(0)"  @click="generateBills('ReleaseProcurement',2,listArr)">下达请购</a>
                                    </a-menu-item>
                                </template>
                            </a-menu>
                        </a-dropdown>
                    </template>
                    <template slot="moreBtn">
                         <a-col class="btn-item" :class="[-1,0].includes(voucherState) ? 'btns-disable':''">
                            <a-dropdown class="btns" key="sheng" style="display:block">
                                <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                                    <a-icon class="btns-icon" type="snippets" />
                                    <div class="btns-text">合拆
                                        <a-icon type="down" />
                                    </div>
                                </a>
                                <!-- <a-menu v-if="voucherState==1" slot="overlay"> -->
                                <a-menu slot="overlay">
                                    <template v-if="[-1,0].includes(voucherState)">
                                        <a-menu-item key="0">
                                            <a href="javascript:void(0)" >
                                              <span :class="'color-gray'">合并</span>
                                            </a>
                                        </a-menu-item>
                                        <a-menu-item key="1">
                                            <a href="javascript:void(0)">
                                              <span :class="'color-gray'">拆分</span>
                                            </a>
                                        </a-menu-item>
                                    </template>
                                    <template v-else>
                                        <a-menu-item key="0">
                                            <a href="javascript:void(0)" @click="merge">
                                                <span>合并</span>
                                            </a>
                                        </a-menu-item>
                                        <a-menu-item key="1">
                                            <a href="javascript:void(0)" @click="split">
                                                <span>拆分</span>
                                            </a>
                                        </a-menu-item>
                                    </template>
                                </a-menu>
                            </a-dropdown>
                         </a-col>
                    </template>
                    <!-- <template slot="shengdan">
                        <a-dropdown class="btns" key="sheng" style="display:block">
                            <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                                <a-icon class="btns-icon" type="snippets" />
                                <div class="btns-text">生单
                                    <a-icon type="down" />
                                </div>
                            </a>
                            <a-menu v-if="voucherState==1" slot="overlay">
                                <a-menu-item key="0">
                                    <a href="javascript:void(0)" @click="generateBills('ProductionWork')">生成加工单</a>
                                </a-menu-item>
                            </a-menu>
                        </a-dropdown>
                    </template> -->
                </btns-wrapper>
            </div>
            <div ref="print" class="documents-wrapper" id="documents-wrapper">
                <h3 class="text-center">
                    {{voucherTitle}}
                </h3>
                <section v-show="showModel=='list'">
                    <!--列表-->
                    <dynamicList ref="dyList" :basePostData="basePostData" :sourceCode="sourceCode" @switchList="switchList" @dblclick="getIdByData" :reportCode="reportCodeList"></dynamicList>
                </section>
                <section v-show="showModel=='order'">
                    <div><span class="audit-status" v-show="voucherState==0">待审核</span><span class="audit-status" v-show="voucherState==1 || voucherState==10">{{voucherState==1?'已审核':'关闭'}}</span></div>
                    <a-form-model :layout="formLayout">
                        <div class="header-box">
                            <order-dynamic-form :FormData="orderHeaderData" @changetime="onChangeTime" @clickItem="setValue"></order-dynamic-form>
                            <div class="edit-mask-header" v-show="editMask">
                                <!-- 遮罩（点击修改关闭遮罩） -->
                            </div>
                        </div>

                        <div class="search-btn-box-gw">
                            <div class="item-small" ref="planLi">
                                <ul>
                                    <li class="item-plan" :class="planActive == 0?'active':''" @click="onUserSearchChange(0)">所有</li>
                                    <li class="item-plan" :class="planActive == 1?'active':''" @click="onUserSearchChange(1)">采购计划</li>
                                    <li class="item-plan" :class="planActive == 2?'active':''" @click="onUserSearchChange(2)">生产计划</li>
                                    <li class="item-plan" :class="planActive == 3?'active':''" @click="onUserSearchChange(3)">委外计划</li>
                                </ul>
                            </div>
                            <div class="item-small-down" v-if="showDownPlan" @click="showDownPlanFun">
                                <a-icon v-if="iconDirection" type="down" />
                                <a-icon v-else type="up" />
                            </div>
                        </div>

                        <div class="table-box">
                            <a-table :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"  id="bills_tb" :columns="columns" :data-source="dataSource" :customRow="customClick" :scroll="{ x: 1000, y: 347 }" :pagination="false" @change="onTableChange" :size="small" bordered>
                                <template slot="number" v-if="isRouterAlive" slot-scope="text, record, index">
                                    <div v-if="index == dataSource.length-1">
                                        合计
                                    </div>
                                    <div v-else>
                                        {{index+1}}
                                    </div>
                                </template>
                                <template v-for="col in slotArray" :slot="col" slot-scope="text, record,index">
                                    <div data-key="">
                                        <editable-cell v-if="isRouterAlive" :checkType="checkType" :text="text" :col="col" :index="index" :record="record" :dataSource="dataSource" :unitsDataDetails="unitsDataDetails" :unitsAssistSelect="unitsAssistSelect" :dynamicAllData="dynamicFormData" :dynamicFormDataMap="dynamicFormDataMap"  @choiceAddData="choiceAddData(index,col,$event)" @change="onCellChange(index, col, $event)" @newAddData="handleAdd" />
                                    </div>
                                </template>
                            </a-table>
                            <div class="edit-mask edit-mask-selection" v-show="editMask">
                                <!-- 遮罩（点击修改关闭遮罩） -->
                            </div>
                        </div>
                        <div class="footer-box">
                            <order-dynamic-form :FormData="orderFooterData"  @changetime="onChangeTime" @clickItem="setValue"></order-dynamic-form>
                            <div class="edit-mask-footer" v-show="editMask">
                                <!-- 遮罩（点击修改关闭遮罩） -->
                            </div>
                        </div>
                    </a-form-model>
                </section>
                <section v-show="showModel=='detail'">
                    <!--明细-->
                    <dynamicListDetails ref="detailSearchRef" :reportCode="reportCodeDetail" :componentType="1" :basePostData="basePostData"></dynamicListDetails>
                </section>
                <section v-show="showModel=='statistical'">
                    <!--统计-->
                    <dynamicListDetails ref="statisticalSearchRef" :reportCode="reportCodeStatistical" :componentType="2" :basePostData="basePostData"></dynamicListDetails>
                </section>
            </div>
            <div class="contextmenu-box">
                <!-- 右键菜单 -->
                <ul v-show="visible" :style="{left:left+'px',top:top+'px'}" class="contextmenu">
                    <li @click="handleAdd()">新增行</li>
                    <li @click="handleDelete()">删除行</li>
                    <!-- <li @click="handleCopy()">复制行</li> -->
                </ul>
            </div>
            <drawerBox ref="searchList" :unitData="unitData" :unitsData="unitsData" :unitsDataDetails="unitsDataDetails" @editClickOrder="editClickOrder"></drawerBox>
        </div>

        <!--加载中-->
        <div class="loading-wrapper" v-show="loading">
            <a-spin class="loading-content" tip="加载中..." />
        </div>
        <!--用做横向打印-->
        <!-- <div v-html="stylePrint"></div> -->
        <print-modal ref="printDom" v-if="printVisible" :incomingPrintData="incomingPrintData" @cancelPrint="cancelPrint"></print-modal>

        <!--生单弹窗-->
        <rawListModal ref="purchaseInRef"></rawListModal>
        <!-- 拆分弹窗 -->
        <split-material v-if="visibleSplit" ref="splitmaterial" :splitData="splitData" :data-source="dataSource" @close="close" @splitSubmit="splitSubmit"></split-material>

    </div>
</template>
<script>


import { save, examine, remove, getCode, submitOrder,setMerge ,setSplit} from '@/api/production/productionOrder';
import pro from '@/mixins/procurement/pro';
import rawListModal from '@/components/productionModal/rawListModal.vue';
import splitMaterial from '../splitMaterial'
import { createLogger } from 'vuex';

export default {
    components: { rawListModal,splitMaterial },
    mixins: [pro],
    data () {
        return {
            sourceCode: 'MasterProductionSchedule',
            reportCodeDetail: 'ProductionOrder_Detail_Report',
            reportCodeStatistical: 'ProductionOrder_Statistic_Report',   //统计code
            reportCodeList: 'ProductionOrder_List_Report',              //列表code

            isDetailCrmId: true,//隐藏明细中的客户字段

            checkType: 'is_made_self,is_made_request',//生产耗用
            selectedRowKeysList: [],
            selectedRowKeys: [],
            visibleSplit:false,
            splitData:'',
            dataSource:[],
            n:1,
            listArr:[],
            planActive : 0,
            num:0,//判断下达是否可以点击
        };
    },
    created () {
        if(this.n==1){
            this.dataSource = this.$store.state.order.mrpBackData
            if(this.$store.state.order.mrpBackData.length > 0){
                this.onUserSearchChange(0)
                this.newForecasts()
            } else{
                this.getIdByData()
            }
        }

        // this.getIdByData();//获取最新一条数据
    },
    activated(){
        // this.getIdByData()
        if(this.n==1){
            this.dataSource = this.$store.state.order.mrpBackData
            if(this.$store.state.order.mrpBackData.length > 0){
                this.onUserSearchChange(0)
                this.newForecasts()
            } else{
                this.getIdByData()
            }
        }
    },

    methods: {
      close(value) {
        this.visibleSplit = value
      },
      splitSubmit(list) {
        let data = this.formatDataSource(list)
        setSplit(data).then(res => {
          if (res.code === 200) {
            this.$message.success('拆分成功');
            this.getIdByData();
            this.$refs.splitmaterial.close()
            this.selectedRowKeysList = [];
            this.selectedRowKeys = [];
          }
        })
      },
        split() {
            if(this.selectedRowKeysList.length==0){
                this.$message.warning('请选择拆分的物料')
                return
            }
            if(this.selectedRowKeysList.length>1){
                this.$message.warning ('只能选择一种物料拆分')
                return
            }
            this.visibleSplit = true
            this.splitData=this.selectedRowKeysList[0]
            // this.dataSource.forEach(item=>{
            //     if(item.bussessPlan==this.selectedRowKeysList[1]){
            //         this.splitData=item
            //     }
            // })
        },
        // 判断点击的是哪一个生成订单能够触发
        isTrueFn(rows){
            this.num = rows[0].bussessPlanId;
            console.log(this.num);
        },
        onSelectChange(selectedRowKeys,rows) {
            if(rows.length>0){
                this.isTrueFn(rows)
            }

            let PlanId1 = []
            let PlanId2 = []
            let PlanId3 = []
            for (let index = 0; index < rows.length; index++) {
                if(rows[index].bussessPlanId == 1) PlanId1.push(rows[index].bussessPlanId);
                if(rows[index].bussessPlanId == 2) PlanId2.push(rows[index].bussessPlanId);
                if(rows[index].bussessPlanId == 3) PlanId3.push(rows[index].bussessPlanId);
            }
            if(PlanId1.length != rows.length && PlanId2.length != rows.length && PlanId3.length != rows.length) {
                this.num = 0;
            } else {
                if(PlanId1.length == rows.length) this.num = 1;
                if(PlanId2.length == rows.length) this.num = 2;
                if(PlanId3.length == rows.length) this.num = 3;
            }


            let arr = []
            this.listArr=rows;
            this.selectedRowKeys = selectedRowKeys
            this.dataSource.forEach(i => {
                rows.forEach(j => {
                    if (i.id === j.id) {
                        arr.push(i)
                    }
                })
            })
            this.selectedRowKeysList = [...new Set(arr)]
        },
        merge() {
            if(this.selectedRowKeysList.length < 2){
                this.$message.warning('请至少选择2条物料合并!'); return
            }
            let arr = this.selectedRowKeysList.map(item => item.inventoryCode);
            if ([...new Set(arr)].length > 1) {
                this.$message.warning('不同物料，不能合并！'); return
            }
            const data = this.formatDataSource(this.selectedRowKeysList);
            setMerge(data).then(res => {
                if (res.code === 200) {
                    this.$message.success('合并成功');
                    this.getIdByData();
                    this.selectedRowKeysList = [];
                    this.selectedRowKeys = [];
                }
            });
        },
        //这是新生单方法，原来的方法在混入pro
        generateBills1 () {
            this.$refs.purchaseInRef.purchaseShowModel(3);
        },

        //新增预测单
        newForecast(){
            this.showModel = 'order';
            this.editMask = false;
            this.loading = false;
            this.voucherState = -1;
            this.sourceVoucherData = {};//清空来源数据
            this.initForm(1);
        },
        //////新增预测单
        newForecasts () {
            this.showModel = 'order';
            this.editMask = false;
            this.loading = false;
            this.voucherState = -1;
            this.sourceVoucherData = {};//清空来源数据
            this.initForm(2);
        },
        //保存
        submit (requestData) {
            requestData.createUserId = this.$store.state.user.info.id
            requestData.createUserName = this.$store.state.user.info.name
            requestData.dataSource = "RequirementPlan"

            requestData.orderDetailList.forEach(element=>{
                element.baseUnit = element.baseUnitId ? element.baseUnitId : element.baseUnit_temp_id
            })
            save(requestData).then(response => {
                if (response.code === 200) {
                    this.$message.success('保存成功');
                    this.editMask = true;
                    this.isSaveRun = true;
                    if (!this.orderId) {
                        this.getIdByData(); //获取最新一条数据
                    }
                } else {
                    this.$message.error(response.message);
                    this.isSaveRun = true;
                }
            }).catch((e) => {
                this.isSaveRun = true;
            })
        },
        //单据提交
        submitOrder (type) {
            let data = {
                id: this.orderId,
                status: type,//状态 -1:撤回提交,0:提交
            }
            console.log(this.orderId);
            if (!this.orderId) {
                this.$message.warning('该单据未保存不需要提交');
                return;
            }
            if (this.voucherState == -1 && type == -1) {
                this.$message.warning('该单据未提交无需撤回提交');
                return;
            }
            submitOrder(data).then(res => {
                if (res.code === 200) {
                    if (type == 0) {
                        this.$message.success('提交成功');
                    } else {
                        this.$message.success('撤回提交成功');
                    }
                    this.getIdByData();
                }
            })
        },
        //审核
        auditClick (type) {
            let requestData = {
                id: this.orderId,
                status: type
            }
            examine(requestData).then((response) => {
                if (response.code === 200) {
                    const backData = response.data;
                    if (type == 1) {
                        this.$message.success('审核成功');
                        this.getIdByData();
                    }
                    if (type == 0) {
                        this.$message.success('弃审成功');
                        this.getIdByData();
                    }
                } else {
                    // this.$message.warning(response.message);
                }
            })
        },
        //删除
        remove (postData) {
            remove(postData).then(response => {
                if (response.code === 200) {
                    this.$message.success('删除成功');
                    this.orderId = '';
                    this.voucherState = 0;
                    this.getIdByData();//获取最新一条数据
                } else {
                    this.$message.error(response.message);
                }
            })
        },
        //获取单据编号
        getCode () {
            getCode().then((res) => {
                if (res.code == 200) {
                    this.receiptNumber = res.message;
                    for (let i = 0; i < this.orderHeaderData.length; i++) {
                        if (this.orderHeaderData[i].code == 'voucherCode') {
                            this.$set(this.orderHeaderData[i], 'onEdit', false)
                            this.$set(this.orderHeaderData[i], 'value', this.receiptNumber)
                        }
                    }
                } else {
                    // this.$message.warning(res.message);
                }
            });
        },
        //切换业务计划
        onUserSearchChange (type) {
            this.planActive = type;
            let dataSource = [];
            let dataSourceList = []
            if(type != 0){
                if(this.$store.state.order.mrpBackData.length === 0){
                    // dataSourceList = this.$store.state.order.mrpBackDataCopy.filter((element,index)=> {
                    //     if(element){
                    //         if(type == element.bussessPlanId){
                    //             return {
                    //                 ...element,
                    //                 baseUnit : element.baseUnitName,
                    //                 baseUnit_temp_id : element.baseUnit,

                    //                 operationQuantity: element.baseQuantity,
                    //                 operationNumber: element.baseQuantity,
                    //                 number: index + 1
                    //             }
                    //         }
                    //     }
                    // });
                    this.$store.state.order.mrpBackDataCopy.forEach((element,index)=>{
                        if(element){
                            if(type == element.bussessPlanId){
                                dataSourceList.push({
                                    ...element,
                                    baseUnit_temp_id : element.baseUnit,
                                    baseUnit : element.baseUnitName,
                                    operationQuantity: element.baseQuantity,
                                    operationNumber: element.baseQuantity,
                                    number: index + 1
                                })
                            }
                        }
                    })
                    console.log(dataSourceList);
                    //补足表格
                    if (dataSourceList.length < this.dataSourceNumber) {
                        for (let i = dataSourceList.length; i < this.dataSourceNumber; i++) {
                            let array = {
                                number: i + 1,
                            };
                            dataSourceList.push(array);
                        }
                    } else {
                        for (let i = 0; i < 2; i++) {
                            let array = {
                                number: i + 1,
                            };
                            dataSourceList.push(array);
                        }
                    }
                    this.dataSource = dataSourceList
                } else {
                    dataSource = this.$store.state.order.mrpBackData.filter((element,index)=> {
                        if(element){
                            if(type == element.bussessPlanId){
                                return {
                                    ...element,
                                    baseUnit : element.baseUnitName,
                                    baseUnit_temp_id : element.baseUnit,
                                    operationQuantity: element.baseQuantity,
                                    operationNumber: element.baseQuantity,
                                    number: index + 1
                                }
                            }
                        }
                    });
                    //补足表格
                    if (dataSource.length < this.dataSourceNumber) {
                        for (let i = dataSource.length; i < this.dataSourceNumber; i++) {
                            let array = {
                                number: i + 1,
                            };
                            dataSource.push(array);
                        }
                    } else {
                        for (let i = 0; i < 2; i++) {
                            let array = {
                                number: i + 1,
                            };
                            dataSource.push(array);
                        }
                    }
                    this.dataSource = dataSource
                }
            } else {
                if(this.$store.state.order.mrpBackData.length === 0){
                    dataSourceList = this.$store.state.order.mrpBackDataCopy.filter((element,index)=> {
                        return {
                            ...element,
                            baseUnit : element.baseUnitName,
                            baseUnit_temp_id : element.baseUnit,
                            operationQuantity: element.baseQuantity,
                            operationNumber: element.baseQuantity,
                            number: index + 1
                        }
                    });
                    //补足表格
                    if (dataSourceList.length < this.dataSourceNumber) {
                        for (let i = dataSourceList.length; i < this.dataSourceNumber; i++) {
                            let array = {
                                number: i + 1,
                            };
                            dataSourceList.push(array);
                        }
                    } else {
                        for (let i = 0; i < 2; i++) {
                            let array = {
                                number: i + 1,
                            };
                            dataSourceList.push(array);
                        }
                    }
                    this.dataSource = dataSourceList
                } else {
                    dataSource = this.$store.state.order.mrpBackData.filter((element,index)=> {
                        return {
                            ...element,
                            baseUnit : element.baseUnitName,
                            baseUnit_temp_id : element.baseUnit,
                            operationQuantity: element.baseQuantity,
                            operationNumber: element.baseQuantity,
                            number: index + 1
                        }
                    });
                    //补足表格
                    if (dataSource.length < this.dataSourceNumber) {
                        for (let i = dataSource.length; i < this.dataSourceNumber; i++) {
                            let array = {
                                number: i + 1,
                            };
                            dataSource.push(array);
                        }
                    } else {
                        for (let i = 0; i < 2; i++) {
                            let array = {
                                number: i + 1,
                            };
                            dataSource.push(array);
                        }
                    }
                    this.dataSource = dataSource
                }
            }

            this.addTotal();//添加合计
        }
    }
};
</script>
<style lang="less" scoped>
    @import '~@/style/purchase/voucher.less';
     .requisition-set-wrapper {
        width:calc(100% - 40px);
        left:40px;
    }
    .edit-mask-selection {
      left: 60px !important; /* 避开复选框区域 */
      width: calc(100% - 60px - 17px) !important; /* 重新计算宽度 */
    }
    /* 强制显示复选框列 */
    .ant-table-selection-column {
      z-index: 2 !important;
    }

</style>
